iT邦幫忙

DAY 13
0

Java重點學習筆記系列 第 13

Java重點筆記十一:Java的日期與時間類別(三)

  • 分享至 

  • xImage
  •  

除了可以用SimpleDateFormat類別來格式化時間之外,也可以透過printf()來實現。

請看以下程式:

Date date = new Date();

String str = String.format("Current Date/Time : %tc", date );

System.out.printf(str);

重點在"%tc","%t"代表時間,"c"是格式代碼,代表完整日期日間。格式代碼有以下各種:

Character	Description	Example
c	Complete date and time	Mon May 04 09:51:52 CDT 2009
F	ISO 8601 date	2004-02-09
D	U.S. formatted date (month/day/year)	02/09/2004
T	24-hour time	18:05:19
r	12-hour time	06:05:19 pm
R	24-hour time, no seconds	18:05
Y	Four-digit year (with leading zeroes)	2004
y	Last two digits of the year (with leading zeroes)	04
C	First two digits of the year (with leading zeroes)	20
B	Full month name	February
b	Abbreviated month name	Feb
m	Two-digit month (with leading zeroes)	02
d	Two-digit day (with leading zeroes)	03
e	Two-digit day (without leading zeroes)	9
A	Full weekday name	Monday
a	Abbreviated weekday name	Mon
j	Three-digit day of year (with leading zeroes)	069
H	Two-digit hour (with leading zeroes), between 00 and 23	18
k	Two-digit hour (without leading zeroes), between 0 and 23	18
I	Two-digit hour (with leading zeroes), between 01 and 12	06
l	Two-digit hour (without leading zeroes), between 1 and 12	6
M	Two-digit minutes (with leading zeroes)	05
S	Two-digit seconds (with leading zeroes)	19
L	Three-digit milliseconds (with leading zeroes)	047
N	Nine-digit nanoseconds (with leading zeroes)	047000000
P	Uppercase morning or afternoon marker	PM
p	Lowercase morning or afternoon marker	pm
z	RFC 822 numeric offset from GMT	-0800
Z	Time zone	PST
s	Seconds since 1970-01-01 00:00:00 GMT	1078884319
Q	Milliseconds since 1970-01-01 00:00:00 GMT	1078884319047

再看一下以下的例子:

System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);

輸出如下:

Due date: October 12, 2014

很明顯這又一種拆解Date類別的方法,格式是以"%"開頭,以"$"結尾,後面再加格式代碼。"%1$s"就是第一個變數,屬於字串類型。"%2$"是第二個變數,"t"是時間類型,"B"是完整月名。後面的也是以"%2$"開頭,代表也是從第二個變數提出。

還有一種表示方式是用"<",代表跟前著一樣,以下的例子跟上面的例子一樣:

System.out.printf("%s %tB %<te, %<tY", "Due date:", date);

上一篇
Java重點筆記十:Java的日期與時間類別(二)
下一篇
Java重點筆記十二:Java的日期與時間類別(四)
系列文
Java重點學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言